package com.schedule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schedule.config.security.component.JwtTokenUtil;
import com.schedule.mapper.AdminMapper;
import com.schedule.mapper.RoleMapper;
import com.schedule.pojo.Admin;
import com.schedule.pojo.AdminRegisterParam;
import com.schedule.pojo.RespBean;
import com.schedule.pojo.Role;
import com.schedule.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author star
 * @since 2021-12-03
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 登录之后返回token
     * @param accountStr
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String accountStr, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");

        System.out.println("登录--用户名："+accountStr);
        System.out.println("登录--密码："+password);
        System.out.println("登录--验证码："+code);
        //判断验证码是否为空，或忽略大小写验证
        if(StringUtils.isEmpty(code)||!captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入错误，请重新输入！");
        }
//        return  loginWithoutCode(accountStr, password);
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(accountStr);

        System.out.println("数据库用户信息: "+userDetails);
        if(null==userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确");
        }
        if(!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员！");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken=new
                UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap=new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",tokenMap);
    }

    /**
     * 根据用户名获取用户
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {

        return adminMapper.selectOne(new QueryWrapper<Admin>()
                .eq("userName",username)
                .eq("enabled",true));
    }

    @Override
    public Admin getAdminByPhoneNum(String phoneNum) {
        return adminMapper.selectOne(new QueryWrapper<Admin>()
                .eq("phoneNum",phoneNum)
                .eq("enabled",true));
    }

    /**
     * 根据用户名模糊查询用户
     * @param username
     * @return
     */
    @Override
    public List<Admin> fuzzyQueryAdminByUserName(String username) {
        return adminMapper.selectList(new QueryWrapper<Admin>().like("userName",username));
    }

    /**
     * 根据手机号模糊查询用户
     * @param phoneNum
     * @return
     */
    @Override
    public List<Admin> fuzzyQueryAdminByPhoneNum(String phoneNum) {
        return adminMapper.selectList(new QueryWrapper<Admin>().like("phoneNum",phoneNum));
    }


    /**
     * 根据用户id查询角色列表
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    /**
     * 添加用户信息
     * @param adminRegisterParam
     * @return
     */
    @Override
    public boolean add(AdminRegisterParam adminRegisterParam) {
        //密码加密
        adminRegisterParam.setPassword(passwordEncoder.encode(adminRegisterParam.getPassword()));
        if(adminMapper.add(adminRegisterParam)>=1){
            return true;
        }
        return false;
    }

    /**
     * 根据id删除用户信息
     * @param Aid
     * @return
     */
    @Override
    public Integer deleteById(Integer Aid) {
        return adminMapper.deleteById(Aid);
    }

    /**
     * 获取当前用户
     * @return
     */
    @Override
    public Admin getCurrentAdmin() {
        return ((Admin) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal());
    }

    /**
     * 验证用户密码
     * @param password
     * @return
     */
    @Override
    public boolean verifyPassword(String password) {
        Admin currentAdmin = getCurrentAdmin();
        return null != currentAdmin && passwordEncoder.matches(password, currentAdmin.getPassword());
    }

//    /**
//     * 无验证码登录
//     * @param accountStr
//     * @param password
//     * @return
//     */
//    @Override
//    public RespBean loginWithoutCode(String accountStr, String password) {
//        //登录
//        UserDetails userDetails = userDetailsService.loadUserByUsername(accountStr);
//
//        System.out.println("数据库用户信息: "+userDetails);
//        if(null==userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
//            return RespBean.error("用户名或密码不正确");
//        }
//        if(!userDetails.isEnabled()){
//            return RespBean.error("账号被禁用，请联系管理员！");
//        }
//        //更新security登录用户对象
//        UsernamePasswordAuthenticationToken authenticationToken=new
//                UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
//        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        //生成token
//        String token = jwtTokenUtil.generateToken(userDetails);
//        Map<String,String> tokenMap=new HashMap<>();
//        tokenMap.put("token",token);
//        tokenMap.put("tokenHead",tokenHead);
//        return RespBean.success("登录成功",tokenMap);
//    }


}
